package com.itheima.nio.buffer.demo10;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NioServerSelectorDemo10 {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress("127.0.0.1", 8585));
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true){
            int select = selector.select();
            if (select != 0){
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()){
                    SelectionKey selectionKey = iterator.next();
                    if (selectionKey.isAcceptable()){
                        ServerSocketChannel serverSocketChannel1 = (ServerSocketChannel) selectionKey.channel();
                        SocketChannel socketChannel = serverSocketChannel1.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    } else if (selectionKey.isReadable()){
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        int read = socketChannel.read(byteBuffer);
                        while (read > 0){
                            byteBuffer.flip();
                            byte[] bytes = byteBuffer.array();
                            System.out.println(new String(bytes, 0, read, "UTF-8"));
                            byteBuffer.clear();
                            read = socketChannel.read(byteBuffer);
                        }
                        ByteBuffer byteBuffer1 = ByteBuffer.wrap("收到".getBytes("UTF-8"));
                        socketChannel.write(byteBuffer1);
                        socketChannel.close();
                    }
                    iterator.remove();
                }
            }
        }
    }
}
